/**
 * Created by DevilsEyes on 2016/4/22.
 */
//courseDetail
define(['upload', 'preview', 'layer', 'ex'], function (upload, preview, layer, ex) {
    'use strict';

    var formatFile = function (files) {
        return {
            name: files.rename || files.title || files.name,//显示用文件名
            type: files.type,//Type
            path: files.path,//实际文件名
            size: files.size//文件大小
        }
    };

    var imgUploader = {
        uploader: null,
        queue: [],
        $btn: null,
        init: function () {
            var id = 'courseDetailImgUpload';
            var _this_ = this;

            this.queue = [];
            this.uploader && this.uploader.destroy && this.uploader.destroy();
            this.$btn && this.$btn.remove();
            this.$btn = $('<div id="' + id + '">');
            $('body').append(this.$btn);

            this.uploader = new upload.Uploader({
                browse_button: id, //触发文件选择对话框的按钮，为那个元素id
                url: '/file/upload' //服务器端的上传页面地址
            });

            this.uploader.init();

            this.uploader.bind('FilesAdded', function (uploader, files) {
                files.some(function (file) {
                    _this_.add(file);
                });
            });

            this.uploader.bind('UploadProgress', function (uploader, file) {
                var index = null;
                var t = _this_.queue.some(function (v, i) {
                    index = i;
                    return v.id == file.id;
                });
                _this_.queue[index].percent = file.percent;
                _this_.sync();
            });

            this.uploader.bind('FileUploaded', function (uploader, file, res) {
                var index = null;
                var data = JSON.parse(res.response).file;
                var t = _this_.queue.some(function (v, i) {
                    index = i;
                    return v.id == file.id;
                });
                URL.revokeObjectURL(_this_.queue[index].url);
                _this_.queue[index].path = data.path;
                _this_.queue[index].url = '/file/view/' + data.path;
                _this_.queue[index].upload = true;
                _this_.sync();
            });

            this.uploader.bind('UploadComplete', function () {
                vm.img.isUploading = false;
            });

            this.sync();
        },
        add: function (file) {
            var _this_ = this;
            var native_file = file.getNative();

            preview(
                native_file,
                function (img) {

                    // console.dir(file);
                    // console.dir(img);
                    // console.log(img.currentSrc);

                    _this_.queue.push({
                        id: file.id,
                        path: '',
                        type: native_file.type,
                        title: native_file.name,
                        url: img.currentSrc,
                        size: native_file.size,
                        upload: false,
                        percent: 0
                    });
                    _this_.sync();
                },
                {noRevoke: true}
            )
        },
        remove: function (index) {
            var target = this.queue.splice(index, 1)[0];
            var id = target.id;
            if (target.upload == false) {
                var file = this.uploader.getFile(id);
                this.uploader.removeFile(file);
            }
            this.sync();
        },
        move: function (index, direction) {
            var swap = null;
            var temp = null;
            switch (direction) {
                case 'up':
                {
                    if (index == 0)return;
                    temp = this.queue[index];
                    swap = this.queue[index - 1];
                    this.queue.splice(index - 1, 2, temp, swap);
                    return this.sync();
                }
                case 'down':
                {
                    if (index == (this.queue.length - 1))return;
                    temp = this.queue[index];
                    swap = this.queue[index + 1];
                    this.queue.splice(index, 2, swap, temp);
                    return this.sync();
                }
            }
        },
        start: function () {
            vm.img.isUploading = true;
            this.uploader.start();
        },
        sync: function () {
            vm.img.avaliable = this.queue.some(function (v) {
                return v.upload == false;
            });
            vm.imgList = ex.copy(this.queue);
        },
        pushData: function (list) {
            this.queue = list.map(function (o) {
                return {
                    id: o.path,
                    path: o.path,
                    type: o.type,
                    title: o.name,
                    url: '/file/view/' + o.path,
                    size: o.size,
                    upload: true,
                    percent: 100
                }
            });
            this.sync();
        },
        get: function () {
            return ex.copy(this.queue);
        }
    };
    var attachmentUploader = {
        uploader: null,
        queue: [],
        $btn: null,
        init: function () {
            var id = 'courseDetailAttachmentUpload';
            var _this_ = this;
            this.queue = [];
            this.uploader && this.uploader.destroy && this.uploader.destroy();
            this.$btn && this.$btn.remove();
            this.$btn = $('<div id="' + id + '">');
            $('body').append(this.$btn);

            this.uploader = new upload.Uploader({
                browse_button: id, //触发文件选择对话框的按钮，为那个元素id
                url: '/file/upload' //服务器端的上传页面地址
            });

            this.uploader.init();

            this.uploader.bind('FilesAdded', function (uploader, files) {
                files.some(function (file) {
                    _this_.add(file);
                });
            });

            this.uploader.bind('UploadProgress', function (uploader, file) {
                var index = null;
                var t = _this_.queue.some(function (v, i) {
                    index = i;
                    return v.id == file.id;
                });
                _this_.queue[index].percent = file.percent;
                _this_.sync();
            });

            this.uploader.bind('FileUploaded', function (uploader, file, res) {
                var index = null;
                var data = JSON.parse(res.response).file;
                var t = _this_.queue.some(function (v, i) {
                    index = i;
                    return v.id == file.id;
                });
                _this_.queue[index].path = data.path;
                _this_.queue[index].upload = true;
                _this_.sync();
            });

            this.uploader.bind('UploadComplete', function () {
                vm.attachment.isUploading = false;
            });
            this.sync();
        },
        add: function (file) {
            var native_file = file.getNative();
            this.queue.push({
                id: file.id,
                path: '',
                type: native_file.type,
                title: native_file.name,
                rename: file.name,
                size: native_file.size,
                upload: false,
                percent: 0
            });
            this.sync();
        },
        remove: function (index) {
            var target = this.queue.splice(index, 1)[0];
            var id = target.id;
            if (target.upload == false) {
                var file = this.uploader.getFile(id);
                this.uploader.removeFile(file);
            }
            this.sync();
        },
        move: function (index, direction) {
            var swap = null;
            var temp = null;
            switch (direction) {
                case 'up':
                {
                    if (index == 0)return;
                    temp = this.queue[index];
                    swap = this.queue[index - 1];
                    this.queue.splice(index - 1, 2, temp, swap);
                    return this.sync();
                }
                case 'down':
                {
                    if (index == (this.queue.length - 1))return;
                    temp = this.queue[index];
                    swap = this.queue[index + 1];
                    this.queue.splice(index, 2, swap, temp);
                    return this.sync();
                }
            }
        },
        start: function () {
            vm.attachment.isUploading = true;
            this.uploader.start();
        },
        changeName: function (index, newName) {
            this.queue[index].rename = newName;
            this.sync();
        },
        sync: function () {
            vm.attachment.avaliable = this.queue.some(function (v) {
                return v.upload == false;
            });
            vm.attachmentList = ex.copy(this.queue);
        },
        get: function () {
            return ex.copy(this.queue);
        },
        pushData: function (list) {
            this.queue = list.map(function (o) {
                return {
                    id: o.path,
                    path: o.path,
                    type: o.type,
                    title: o.name,
                    rename: o.name,
                    size: o.size,
                    upload: true,
                    percent: 100
                }
            });
            this.sync();
        }
    };

    var MODE = {
        add: 1,
        edit: 2
    };
    var vm = avalon.define({
        $id: 'courseDetail',

        mode: MODE.add,
        MODE: MODE, //判据

        _id: null,
        title: '',
        tags: '',
        classSelected: [],
        classSelectList: [],
        article: '',

        img: {
            isUploading: false,
            avaliable: false
        },
        attachment: {
            isUploading: false,
            avaliable: false
        },

        UPLOAD: {
            img: 'img',
            attachment: 'attachment'
        },

        __unwatch__: null,

        imgList: [],
        attachmentList: [],

        init: function () {
            vm.mode = MODE.add;
            vm.tags = '';
            vm.title = '';

            vm.classSelected = [];
            $.ajax({
                url: '/api/admin/user/class',
                success: function (obj) {
                    if (obj.code == 0) {
                        vm.classSelectList = obj.list;

                        typeof vm.__unwatch__ == 'function' && vm.__unwatch__();
                        vm.article = '';
                        vm.__unwatch__ = vm.$watch('article', function () {
                            var t = $('textarea').get(0);
                            if (t.scrollHeight >= 80) {
                                t.style.height = t.scrollHeight + 'px';
                            } else {
                                t.style.height = 80;
                            }
                        });
                        imgUploader.init();
                        attachmentUploader.init();
                        setTimeout(function () {
                            $('[data-toggle="checkbox"]').radiocheck();
                        }, 0)
                    }
                }
            });
        },
        initEditMode: function (id) {
            vm._id = id;
            vm.mode = MODE.edit;
            var classReady = new Promise(function (res, rej) {
                $.ajax({
                    url: '/api/admin/user/class',
                    success: function (obj) {
                        if (obj.code == 0) {
                            vm.classSelectList = obj.list;
                            setTimeout(function () {
                                $('[data-toggle="checkbox"]').radiocheck();
                                res();
                            }, 0)
                        }
                    }
                });
            });
            $.ajax({
                url: '/api/admin/course',
                data: {
                    _id: id
                },
                success: function (obj) {
                    if (obj.code != 0) {
                        layer.msg(obj.msg);
                        location.hash = '#!/course/list';
                    } else {
                        var info = obj.info;

                        console.dir(info);
                        classReady.then(function () {
                            vm.classSelected = info.class.split('#');
                        });
                        vm.tags = info.tags;
                        vm.title = info.title;

                        typeof vm.__unwatch__ == 'function' && vm.__unwatch__();
                        vm.article = '';
                        vm.__unwatch__ = vm.$watch('article', function () {
                            var t = $('textarea').get(0);
                            if (t.scrollHeight >= 80) {
                                t.style.height = t.scrollHeight + 'px';
                            } else {
                                t.style.height = 80;
                            }
                        });
                        vm.article = info.article;

                        imgUploader.init();
                        imgUploader.pushData(info.imgs);
                        attachmentUploader.init();
                        attachmentUploader.pushData(info.attachments);
                    }
                }
            })
        },
        start: function ($event, target) {
            switch (target) {
                case vm.UPLOAD.img:
                {
                    return imgUploader.start();
                }
                case vm.UPLOAD.attachment:
                {
                    return attachmentUploader.start();
                }
            }

        },
        select: function ($event, target) {
            switch (target) {
                case vm.UPLOAD.img:
                {
                    return imgUploader.$btn.click();
                }
                case vm.UPLOAD.attachment:
                {
                    return attachmentUploader.$btn.click();
                }
            }
        },
        move: function ($event, index, target, direction) {
            switch (target) {
                case vm.UPLOAD.img:
                {
                    return imgUploader.move(index, direction);
                }
                case vm.UPLOAD.attachment:
                {
                    return attachmentUploader.move(index, direction);
                }
            }
        },
        remove: function ($event, index, target) {
            switch (target) {
                case vm.UPLOAD.img:
                {
                    return imgUploader.remove(index);
                }
                case vm.UPLOAD.attachment:
                {
                    return attachmentUploader.remove(index);
                }
            }
        },
        editAttachmentName: function ($event, $index) {
            layer.prompt({
                formType: 0,
                value: vm.attachmentList[$index].title,
                maxlength: 30
            }, function (value, dialog) {
                attachmentUploader.changeName($index, value);
                layer.close(dialog);
            })
        },

        submit: function (e) {
            e.preventDefault();

            var data = {
                class: vm.classSelected.join('#'),
                title: vm.title,
                tags: vm.tags,
                article: vm.article,
                imgs: imgUploader.get(),
                attachments: attachmentUploader.get()
            };

            if (data.title.length == 0) {
                return layer.msg('必须填写标题');
            }
            if (data.class.length == 0) {
                return layer.msg('必须选择班级');
            }
            if (data.imgs.some(function (v) {
                    console.log(v);
                    return v.upload == false;
                }))return layer.msg('有图片尚未上传!');
            if (data.attachments.some(function (v) {
                    return v.upload == false;
                }))return layer.msg('有附件尚未上传!');

            data.imgs = data.imgs.map(function (v) {
                return formatFile(v);
            });
            data.attachments = data.attachments.map(function (v) {
                return formatFile(v);
            });
            console.dir(data);

            switch (vm.mode) {
                case MODE.add:
                {
                    $.ajax({
                        url: '/api/admin/course',
                        method: 'POST',
                        data: {
                            json: JSON.stringify(data)
                        },
                        success: function (res) {
                            console.dir(res);
                            if (res.code == 0) {
                                layer.msg('新建课件成功!');
                                location.hash = '#!/course/list';
                            }
                        }
                    });
                    return;
                }
                case MODE.edit:
                {
                    data._id = vm._id;
                    $.ajax({
                        url: '/api/admin/course',
                        method: 'PUT',
                        data: {
                            json: JSON.stringify(data)
                        },
                        success: function (res) {
                            if (res.code == 0) {
                                layer.msg('编辑课件成功!');
                                location.hash = '#!/course/list';
                            }
                        }
                    });
                }
            }


        },

        //辅助方法
        formatSize: function (size) {
            var unit = ['B', 'KB', 'MB'];
            var res = '';
            if (unit.some(function (unit) {
                    if (size < 1024) {
                        return res = ('' + size).slice(0, 4).replace(/\.$/, '') + unit;
                    }
                    size = size / 1024;
                })) {
                return res;
            } else {
                return 'to Large';
            }
        }
    });

    return {
        add: function () {
            vm.init();
            // $root.page = temp;
        },
        edit: function (id) {
            vm.initEditMode(id);
        }
    }
});